<template>
    <n-form ref="formRef" :model="formData" :rules="rules">
        <n-form-item label="账号" path="account">
            <n-input
                v-model:value="formData.account"
                :disabled="model === 'update'"
                placeholder="请输入账号"
                clearable
            />
        </n-form-item>
        <n-form-item label="用户名" path="userName">
            <n-input
                v-model:value="formData.userName"
                placeholder="请输入用户名"
                maxlength="20"
                clearable
            />
        </n-form-item>
        <n-form-item v-if="model === 'create'" label="密码" path="password">
            <n-input
                v-model:value="formData.password"
                placeholder="请输入密码"
                maxlength="20"
                clearable
            />
        </n-form-item>
        <n-form-item v-if="type === 'customer'" label="邮箱" path="email">
            <n-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item label="是否冻结">
            <n-switch
                v-model:value="formData.frozen"
                :checked-value="1"
                :unchecked-value="0"
            ></n-switch>
        </n-form-item>
    </n-form>
    <div class="w-full flex justify-end gap-2.5">
        <n-button
            v-if="model === 'create'"
            text
            :focusable="false"
            @click="handleGenerate"
        >
            <template #icon>
                <ReloadCircleOutline />
            </template>
        </n-button>
        <n-button :focusable="false" @click="handleReset">重置</n-button>
        <n-button :focusable="false" type="primary" @click="handleSubmit">
            提交
        </n-button>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";

import { ReloadCircleOutline } from "@vicons/ionicons5";
import { NInput, FormInst, FormRules } from "naive-ui";

import { User } from "@/types/user";
import { UserCreateDto } from "@/service/api/dto/user.dto";

import { uid, random } from "radash";

const props = defineProps<{
    type: "admin" | "customer";
    model: "create" | "update";
    data?: User | null;
}>();

const emits = defineEmits<{
    (e: "submit:data", data: UserCreateDto | User): void;
}>();

const formRef = ref<FormInst>();
const emptyForm: UserCreateDto = {
    account: "",
    userName: "",
    password: "",
    role: props.type === "admin" ? 1 : 0,
    frozen: 0,
};
const formData = reactive<UserCreateDto>(structuredClone(emptyForm));
const rules = reactive<FormRules>({
    account: [
        {
            required: true,
            validator: (_, value: string) => {
                if (!/^[1-9]\d{8}$/.test(value)) {
                    return new Error("账号必须为9位数字");
                }
                return true;
            },
        },
    ],
    userName: [
        {
            required: true,
            validator: (_, value: string) => {
                if (!value) {
                    return new Error("用户名不能为空");
                }
                return true;
            },
        },
    ],
    password: [
        {
            required: true,
            validator: (_, value: string) => {
                if (!/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(value)) {
                    return new Error("密码至少8位，包含字母和数字");
                }
                return true;
            },
        },
    ],
    email: [
        {
            required: true,
            validator: (_, value: string) => {
                if (
                    !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(
                        value
                    )
                ) {
                    return new Error("邮箱格式不正确");
                }
                return true;
            },
        },
    ],
});

onMounted(() => {
    if (props.data) {
        Object.assign(formData, JSON.parse(JSON.stringify(props.data)));
        return;
    }

    console.log(formData);

    Object.assign(formData, structuredClone(emptyForm));
});

const handleGenerate = () => {
    formData.account = random(100000000, 999999999).toString();
    formData.userName = uid(random(4, 10));
    formData.password = uid(random(8, 15));

    const domains = ["@gmail.com", "@163.com", "@qq.com", "@outlook.com"];
    const emailUserName = Array.from(
        { length: Math.floor(Math.random() * 8) + 5 },
        () => {
            const chars =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return chars[Math.floor(Math.random() * chars.length)];
        }
    ).join("");
    const domain = domains[Math.floor(Math.random() * domains.length)];
    formData.email = `${emailUserName}${domain}`;
};

const handleReset = () => {
    if (props.model === "create") {
        Object.assign(formData, structuredClone(emptyForm));
    } else {
        Object.assign(formData, JSON.parse(JSON.stringify(props.data)));
    }
    formRef.value?.restoreValidation();
};

const handleSubmit = async () => {
    try {
        await formRef.value?.validate();
        emits("submit:data", formData);
    } catch (err) {
        return null;
    }
};
</script>

<style scoped></style>
